package com.zz.inventory.controller;

import com.zz.inventory.service.IStudentsService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.nio.charset.StandardCharsets;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;
import java.sql.Timestamp;

@Slf4j
@RestController
public class PathController {
    @Autowired
    IStudentsService studentsService;

    private static final String UPLOAD_DIR = "E:\\RuoYi\\项目\\emulation\\json";

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 数据库表结构假设如下（根据实际调整）：
    // CREATE TABLE exam_results (
    //     id BIGINT AUTO_INCREMENT PRIMARY KEY,
    //     exam_id VARCHAR(50) NOT NULL,
    //     student_name VARCHAR(100),
    //     file_name VARCHAR(255) NOT NULL,
    //     json_content TEXT NOT NULL,
    //     upload_time DATETIME NOT NULL,
    //     file_path VARCHAR(500) NOT NULL
    // );

    @PostMapping("/exam/examlist")
    public String forwardFile(@RequestPart("cocosConfigFile") MultipartFile file) throws IOException {
        String studentName ="";
        String originalFilename = file.getOriginalFilename();
        log.info("开始处理上传文件，原始文件名: {}", originalFilename);
        log.info("文件大小: {} bytes", file.getSize());

        if (file.isEmpty()) {
            log.warn("上传文件为空");
            return "上传文件为空";
        }

        // 创建上传目录
        Path uploadPath = Paths.get(UPLOAD_DIR);
        if (!Files.exists(uploadPath)) {
            log.info("创建上传目录: {}", uploadPath);
            Files.createDirectories(uploadPath);
        }

        // 处理ZIP文件
        if (originalFilename != null && originalFilename.toLowerCase().endsWith(".zip")) {
            log.info("开始解压ZIP文件");
            int jsonFileCount = 0;

            // 解析文件名获取考试ID和学生姓名（根据实际格式调整）
            String[] nameParts = originalFilename.split("_");
            String examId = nameParts.length > 0 ? nameParts[0] : "unknown";
            studentName = nameParts.length > 1 ? nameParts[1] : "unknown";
            System.out.println("姓名"+studentName);
            // 获取原始文件名（不带.zip后缀）
            String baseName = originalFilename.substring(0, originalFilename.lastIndexOf('.'));
            String newFileName = baseName + ".json";
            Path filePath = uploadPath.resolve(newFileName).normalize();

            log.info("新文件名: {}", newFileName);
            log.info("解析后完整路径: {}", filePath);

            try (ZipInputStream zipIn = new ZipInputStream(file.getInputStream())) {
                ZipEntry entry = zipIn.getNextEntry();

                while (entry != null) {
                    if (!entry.isDirectory() && entry.getName().toLowerCase().endsWith(".json")) {
                        // 安全校验
                        if (!filePath.startsWith(uploadPath)) {
                            log.error("非法解压路径: {} → {}", newFileName, filePath);
                            throw new IOException("非法解压路径: " + newFileName);
                        }

                        // 确保父目录存在
                        Path parent = filePath.getParent();
                        if (!Files.exists(parent)) {
                            log.info("创建父目录: {}", parent);
                            Files.createDirectories(parent);
                        }

                        log.info("开始处理JSON文件: {}", filePath.getFileName());

                        // 保存文件
                        Files.copy(zipIn, filePath, StandardCopyOption.REPLACE_EXISTING);
                        log.info("文件保存成功: {}", filePath);

                        // 读取JSON内容
                        String jsonContent = new String(Files.readAllBytes(filePath), StandardCharsets.UTF_8);
                        log.debug("JSON文件内容 (前100字符): {}",
                                jsonContent.length() > 100 ? jsonContent.substring(0, 100) + "..." : jsonContent);
                        // 把json内容修改进数据库
                        studentsService.updateFe(studentName,jsonContent);
                        jsonFileCount++;
                    }
                    zipIn.closeEntry();
                    entry = zipIn.getNextEntry();
                }
            }
            log.info("解压完成，共处理 {} 个JSON文件", jsonFileCount);
            return String.format("解压成功，共处理 %d 个JSON文件，数据已入库", jsonFileCount);
        } else {
            // 处理单个JSON文件（非ZIP情况）
            if (originalFilename != null && originalFilename.toLowerCase().endsWith(".json")) {
                Path filePath = uploadPath.resolve(originalFilename).normalize();
                log.info("文件保存路径: {}", filePath);

                Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
                log.info("文件保存成功: {}", filePath);

                // 读取JSON内容
                String jsonContent = new String(Files.readAllBytes(filePath), StandardCharsets.UTF_8);
                log.debug("JSON文件内容 (前100字符): {}",
                        jsonContent.length() > 100 ? jsonContent.substring(0, 100) + "..." : jsonContent);

                // 把json内容修改进数据库
                studentsService.updateFe(studentName,jsonContent);
                return "JSON文件处理成功: " + originalFilename;
            } else {
                // 非JSON文件直接保存
                Path path = uploadPath.resolve(originalFilename != null ? originalFilename : "unnamed_file").normalize();
                log.info("非JSON文件保存路径: {}", path);
                Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
                log.info("文件保存成功: {}", path);
                return "文件保存成功: " + path.getFileName();
            }
        }
    }


}